package com.cy.store.service.impl;

import com.cy.store.entity.Address;
import com.cy.store.entity.Order;
import com.cy.store.entity.OrderItem;
import com.cy.store.mapper.AddressMapper;
import com.cy.store.mapper.CartMapper;
import com.cy.store.mapper.OrderMapper;
import com.cy.store.service.IAddressService;
import com.cy.store.service.IDistrictService;
import com.cy.store.service.IOrderService;
import com.cy.store.service.ex.*;
import com.cy.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OrderServImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private IAddressService iAddressService;

    @Autowired
    private CartMapper cartMapper;

    @Override
    public Order insertOrder(Integer uid, Integer aid, String username, Integer[] cid) {
        List<CartVO> list = cartMapper.findCartProductByCid(cid);
        long totalPrice = 0L;//定义出订单的总价
        for (CartVO c:list) {
            totalPrice += c.getRealPrice()*c.getNum();
        }
        Order order = new Order();//定义出订单对象
        Address address = iAddressService.findAddressByUid(uid,aid);
        order.setUid(uid);
        order.setTotalPrice(totalPrice);
        order.setRecvName(username);
        order.setRecvAddress(address.getAddress());
        order.setRecvProvince(address.getProvinceName());
        order.setRecvCity(address.getCityName());
        order.setRecvArea(address.getAreaName());
        order.setRecvPhone(address.getPhone());
        order.setStatus(0);
        order.setOrderTime(new Date());
        order.setCreatedTime(new Date());
        order.setCreatedUser(username);
        Integer rows = orderMapper.insertOrder(order);
        if (rows != 1){
            throw new InsertException("插入数据过程中异常！");
        }
        //插入订单项数据
        for (CartVO c:list) {
            OrderItem orderItem = new OrderItem();//创建订单项对象
            orderItem.setOid(order.getOid());
            orderItem.setPid(c.getPid());
            orderItem.setPid(c.getPid());
            orderItem.setTitle(c.getTitle());
            orderItem.setImage(c.getImage());
            orderItem.setNum(c.getNum());
            orderItem.setPrice(c.getPrice());
            orderItem.setCreatedTime(new Date());
            orderItem.setCreatedUser(username);
            rows = orderMapper.insertOrderItem(orderItem);
            if (rows != 1) {
                throw new InsertException("插入数据过程中异常！");
            }
        }
        return order;
    }
}
